package polyu.comp;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class Asensor implements SensorEventListener {
	public static final String TAG_DX = "ValueDx";
	public static final String TAG_DY = "ValueDy";
	public static final String TAG_DZ = "ValueDz";
	private boolean isStarted = false;
	private SensorManager mSensorManager;
	private Sensor mAccelerometer;
	private Handler mHandler;

	// Constructor
	public Asensor(Context context, Handler handler) {
		mHandler = handler;
		mSensorManager = (SensorManager) context
				.getSystemService(Context.SENSOR_SERVICE);
		mAccelerometer = mSensorManager
				.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	}


	// OnSensorChanged
	public void onSensorChanged(SensorEvent sensorEvent) {
		if (sensorEvent.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
			return;

		float dx = sensorEvent.values[0];
		float dy = sensorEvent.values[1];
		float dz = sensorEvent.values[2];

		if (mHandler != null) {
			Message message = mHandler.obtainMessage();
			Bundle bundle = new Bundle();

			bundle.putFloat(TAG_DX, dx);
			bundle.putFloat(TAG_DY, dy);
			bundle.putFloat(TAG_DZ, dz);

			message.setData(bundle);
			mHandler.sendMessage(message);
		}
	}

	public void startListening() {
		if (isStarted)
			return;
		mSensorManager.registerListener(this, mAccelerometer,
				SensorManager.SENSOR_DELAY_UI);
		isStarted = true;
	}

	public void stopListening() {
		if (!isStarted)
			return;
		mSensorManager.unregisterListener(this);
		isStarted = false;
	}


	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// do nothing
	}

}
